from PySide6.QtCore import Signal, Slot, Signal, qDebug, QThread, QMutex, QWaitCondition
from PySide6.QtGui import QAction
from PySide6.QtWidgets import QWidget, QMessageBox, QLabel, QMenuBar, QMainWindow
from Forms.MainForm import MainForm
from Forms.MainWindowForm import MainWindowForm
from . import *
from .SearchFilterWidgets import SearchFilterWidgets
from .MenuWidgets import MenuWidgets
from .ExportDataDialog import ExportDataDialog
from .DarenContactDialog import DarenContactDialog
from Threads.JinritemaiThread import JinritemaiThread
from Threads.BackendApiThread import BackendApiThread
from datetime import datetime


class MainWidgets(QMainWindow):
    respFromJinritemai = Signal(dict)
    downloadProgress = Signal(dict)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.cookies = ''
        self.verifyFp = ''
        self.msToken = ''
        self.screenInfo = ''
        self.userAgent = ''
        self.darens = {}
        self.darenContact = {}
        self.darenPages = 0
        self.darenNum = 0
        self.darenContactNum = 0
        self.darenContactSuccNum = 0
        self.contactMode = 1
        self.contactLimit = 0
        self.jwt = ''
        self.updateDaren = {}

        self.updateDarenInfo = {}
        self.darenNoUpdate = 0

        self.updateDarenContact = {}

        self.setupLoginThread()

        # self.mainUi = MainForm()
        # self.mainUi.setupUi(self)
        # self.menuBar = MenuWidgets(parentWidget=self)
        # self.menuBar.closeApp.connect(self.closeApp)
        # self.menuBar.exportDataDialog.connect(self.showExportDataDialog)
        self.mainUi = MainWindowForm()
        self.mainUi.setupUi(self)
        self.mainUi.actionexit.triggered.connect(self.closeApp)
        self.mainUi.exportData.triggered.connect(self.openExportDataDialog)
        self.mainUi.darenContact.triggered.connect(self.openDarenContactDialog)

        self.resetContactMode()

        self.mainUi.filterBtn.clicked.connect(self.showSearchFilterWidgets)
        self.mainUi.searchBtn.clicked.connect(self.startCollection)
        self.mainUi.pauseBtn.clicked.connect(self.pauseCollection)
        # self.mainUi.closeBtn.clicked.connect(self.closeCollection)
        logging.info('start!!!')
        self.searchFilterWidgets = None
        self.cond = QWaitCondition()
        self.mutex = QMutex()

        self.downloadFromBackendApiThread = None

    def closeApp(self):
        self.close()

    def openExportDataDialog(self):
        self.downloadExportDialog = ExportDataDialog(parentWidget=self)
        self.downloadExportDialog.setWindowTitle("导出数据")
        self.downloadProgress.connect(self.downloadExportDialog.updateDownloadProgress)
        self.downloadExportDialog.download.connect(self.setupDownloadDarenInfoThread)
        self.downloadExportDialog.closeSignal.connect(self.closeExportDataDialog)
        self.downloadExportDialog.show()

    @Slot()
    def closeExportDataDialog(self):
        # 关闭时还在执行写入下载达人信息的线程，需要将子线程关闭
        if self.downloadFromBackendApiThread:
            self.downloadFromBackendApiThread.quit()
        self.downloadExportDialog.close()

    def openDarenContactDialog(self):
        self.darenContactDialog = DarenContactDialog(parentWidget=self)
        self.darenContactDialog.setWindowTitle("采集达人联系方式")
        self.darenContactDialog.download.connect(self.setupDarenContactListThread)
        self.darenContactDialog.closeSignal.connect(self.closeDarenContactDialog)
        self.darenContactDialog.show()

    @Slot(dict)
    def setupDarenContactListThread(self, darensDownloadBody):
        """
        启用下载待获取联系方式的达人列表        
        """
        qDebug(f'开启下载带采集联系方式的达人列表线程: {darensDownloadBody}')
        self.darenContactListThread = BackendApiThread(downloadBody=darensDownloadBody, header={'Content-type': 'application/json', 'Authorization': f'Auth {self.jwt}'})
        self.downloadDarenListThread = QThread()
        self.darenContactListThread.moveToThread(self.downloadDarenListThread)
        self.darenContactListThread.downloadDarenInfoResp.connect(self.downloadDarenContactList)
        self.darenContactListThread.finished.connect(self.downloadDarenContactListFinished)
        self.downloadDarenListThread.started.connect(self.darenContactListThread.downloadDarenContactList)
        self.downloadDarenListThread.start()
        self.darenContactDialog.mainUi.downloadButton.setEnabled(False)
        
    @Slot(dict)
    def downloadDarenContactList(self, uploadRes):
        """
        调用后台下载达人信息接口成功
        """
        logging.info(f'下载带采集联系方式的达人列表成功: {len(uploadRes.get("data", []))}')
        if not uploadRes.get("data", []):
            self.setScrollArea(msg='没有待采集联系方式的达人', scrollArea=self.darenContactDialog)
        else:
            self.darenContact = {}
            self.updateDaren = {}
            for data in uploadRes.get('data', []):
                if len(self.darenContact.keys()) >= self.contactLimit:
                    logging.warning(f'本次只能采集{self.contactLimit}位达人联系方式，所以不再继续从接口返回的达人列表里读取数据了')
                    break
                uid = data.get('uid', 0)
                id = data.get('id', 0)
                nickname = data.get('nickname', '')
                dy_id = data.get('dy_id', '')
                if not uid or not id or not nickname or not dy_id:
                    msg = '没法获取到带采集联系方式的达人id或uid或昵称或dy_id'
                    self.setScrollArea(msg, scrollArea=self.darenContactDialog)
                    logging.error(f'msg - {data}')
                    continue

                self.darenContact[uid] = nickname
                self.updateDaren[uid] = {'id': id, 'nickname': nickname, 'dy_id': dy_id}

    @Slot()
    def downloadDarenContactListFinished(self):
        # logging.info(f'待采集联系方式的达人列表下载完毕: {self.darenContact}')
        self.darenContactNum = len(self.darenContact.keys())
        self.setScrollArea(msg=f'待采集联系方式的达人列表下载完毕本次共采集{self.darenContactNum}位达人联系方式', scrollArea=self.darenContactDialog)
        self.downloadDarenListThread.quit()
        self.downloadDarenListThread.wait()
        self.setupDarenInfoThread()

    @Slot()
    def closeDarenContactDialog(self):
        if hasattr(self, 'downloadDarenListThread') and self.downloadDarenListThread.isRunning():
            self.downloadDarenListThread.quit()
            self.downloadDarenListThread.wait()
        if hasattr(self, 'darenContactThread') and self.darenContactThread.isRunning():
            self.jinritemaiThread.closeContact()
            self.setScrollArea(f'关闭采集达人联系方式', scrollArea=self.darenContactDialog)
        # if self.updateDarenContactThread and self.updateDarenContactThread.isRunning():
        #     self.updateDarenContactThread.quit()
        #     self.updateDarenContactThread.wait()

        self.darenContactDialog.close()

    def getContactMode(self):
        """
        获取contactMode
        """
        self.contactMode = 1
        if self.mainUi.contactModeWechat.isChecked():
            self.contactMode = 2

    def resetContactMode(self):
        """
        重置contactMode
        """
        self.mainUi.contactModeMobile.setChecked(True)
        self.mainUi.contactModeWechat.setChecked(False)
        # self.mainUi.contactModeAll.setChecked(False)
        if self.contactMode == 2:
            self.mainUi.contactModeWechat.setChecked(True)        

    def chkParams(self):
        """
        检查msToken和verifyFp是否存在
        """
        return self.verifyFp and self.msToken

    def parseCookies(self):
        """
        解析cookie，sceenInfo和userAgent
        """
        self.cookies = setting.get('jinritemai', {}).get('cookies', '') if not self.mainUi.lineEdit_cookie.text() else self.mainUi.lineEdit_cookie.text()
        self.screenInfo = setting.get('jinritemai', {}).get('screenInfo', '') if not self.mainUi.lineEdit_screen_info.text() else self.mainUi.lineEdit_screen_info.text()
        self.userAgent = setting.get('jinritemai', {}).get('userAgent', '') if not self.mainUi.lineEdit_user_agent.text() else self.mainUi.lineEdit_user_agent.text()
        if not self.cookies:
            raise ValueError("请输入cookie")
        else:
            for x in self.cookies.split(';'):
                x_split = x.split('=')
                item = x_split.pop(0).replace(" ", "")
                value = ''.join([temp_split.replace(" ", "") if temp_split else '=' for temp_split in x_split])
                if item == 's_v_web_id':
                    self.verifyFp = value.replace(" ", "")
                elif item == 'msToken':
                    self.msToken = value.replace(" ", "")

            if not self.chkParams():
                raise KeyError("没有获取到verifyFp或msToken")
            
    @Slot(dict, int, int, float)
    def darenListResp(self, darenList, page, total, sleep_time):
        """
        达人列表采集成功
        """
        self.darenPages = page
        darenNum = len(darenList)
        self.darenNum += darenNum
        tipsMsg = QLabel(f'本次采集第{page}页的数据（总共{total}条），得到{darenNum}条达人信息。{sleep_time}秒后采集下一页')    
        self.mainUi.scrollArea.widget().layout().addWidget(tipsMsg)
        for daren in darenList:
            nickname = daren.get('author_base', {}).get('nickname', 'nickname')
            uid = daren.get('author_base', {}).get('uid', 'xxx')
            self.darens[uid] = {
                'uid': uid,
                'nickname': nickname,
                'avatar': daren.get('author_base', {}).get('avatar', 'avatar'),
                'fans_num': daren.get('author_base', {}).get('fans_num', 0),
                'level': daren.get('author_base', {}).get('author_level', 0),
                'tag': ','.join(daren.get('author_tag', {}).get('main_cate', [])),
                'mobile': '',
                'wechat': '',
                'dy_id': daren.get('author_base', {}).get('aweme_id', '')
            }
            if daren.get('author_tag', {}).get('contact_icon', ''):
                self.darenContact[uid] = nickname
                self.darenContactNum += 1

            msg = f'采集到{nickname}的数据'
            self.setScrollArea(msg)
            # logging.info(f'采集到{len(self.darens.keys())}')
            logging.info(f'采集到第{page}页的数据，{uid} - {nickname}')

    def setScrollArea(self, msg, scrollArea=None):
        """
        scorllArea
        """
        tipsMsg = QLabel(f'{datetime.now().strftime("%Y-%m-%d %H:%M:%S")} - {msg}') 
        if not scrollArea:
            bar = self.mainUi.scrollArea.verticalScrollBar()
            self.mainUi.scrollArea.widget().layout().addWidget(tipsMsg)
        else:
            bar = scrollArea.mainUi.darenContactScrollArea.verticalScrollBar()
            scrollArea.mainUi.darenContactScrollArea.widget().layout().addWidget(tipsMsg)
        bar.setValue(bar.maximum())

    @Slot()
    def darenListFinished(self):
        """
        采集达人列表页接口完成回调
        """
        self.thread.quit()
        self.thread.wait()
        msg = f'达人列表信息采集完毕。共采集{self.darenPages}页，{self.darenNum}位达人的信息\r\n----------------------------------------'
        self.setScrollArea(msg)
        # if self.jinritemaiThread.is_close:
            # self.setupDarenInfoThread()
        self.setupUploadDarenInfoThread()
        
    def setupDarenInfoThread(self):
        """
        初始化采集达人信息线程
        """
        msg = f'开始采集达人联系方式。本次共采集{self.darenContactNum}位达人的联系方式，系统设定为采集其{"手机号码" if self.contactMode == 1 else "微信号"}'
        self.setScrollArea(msg, scrollArea=self.darenContactDialog)

        self.jinritemaiThread = JinritemaiThread(cookies=self.cookies, verifyFp=self.verifyFp,
                                                        msToken=self.msToken, screenInfo=self.screenInfo,
                                                        ua=self.userAgent, darenUids=self.updateDaren,
                                                        contactMode=self.contactMode, contactLimit=self.contactLimit)
        self.darenContactThread = QThread()
        self.jinritemaiThread.moveToThread(self.darenContactThread)
        self.jinritemaiThread.darenContactResp.connect(self.darenContactInfoResp)
        self.jinritemaiThread.finished.connect(self.darenContactInfoFinished)
        # self.thread.started.connect(self.jinritemaiThread.getDarenContactInfo) 
        self.darenContactThread.started.connect(self.jinritemaiThread.getDarenContactInfoViaManager)   
        self.darenContactThread.start()

    @Slot(dict)
    def darenContactInfoResp(self, contactInfo):
        """
        达人联系信息采集成功回调
        """
        uid = contactInfo.get('uid', '')
        contactMode = 'contact_value'
        contactKey = 'mobile' if self.contactMode == 1 else 'wechat'

        if not uid:
            logging.error(f'采集达人联系方式时uid不存在: {contactInfo}')
        if contactInfo.get('contactInfo', None) is None:
            # msg = f'采集次数受限: {self.jinritemaiThread.contactLimit}'
            # msg = f'采集次数受限: {self.contactLimit}'
            self.contactLimit = self.jinritemaiThread.contactLimit
            msg = f'采集次数受限'
            logging.error(msg)
            self.setScrollArea(msg, scrollArea=self.darenContactDialog)
        elif contactInfo.get('contactInfo', None) is False:
            msg = f'{self.updateDaren[uid]["nickname"]}联系方式采集失败，具体失败原因请查看日志'
            logging.error(msg)
            self.setScrollArea(msg, scrollArea=self.darenContactDialog)
        elif isinstance(contactInfo.get('contactInfo', None), str):
            logging.error(f'contactInfo是个字符串: {self.updateDaren[uid]["nickname"]} - {contactInfo}')
            # msg = f"采集达人信息时接口报错: {self.darens[uid]['nickname']} - {contactInfo.get('contactInfo', None)}"
            msg = f"采集达人信息时接口报错: {self.updateDaren[uid]['nickname']} - {contactInfo.get('contactInfo', None)}"
            logging.error(msg)
            self.updateDarenContact[uid] = {
                'id': self.updateDaren[uid]['id'],
                'nickname': self.updateDaren[uid]['nickname'],
                contactKey: '1'
            }
            self.setScrollArea(msg, scrollArea=self.darenContactDialog)
        else:
            contactInfo = contactInfo.get('contactInfo', {}).get('contact_info', {})
            # self.darens[uid][contactKey] = contactInfo.get(contactMode)
            # msg = f'成功采集到{self.darens[uid]["nickname"]}的联系方式，还能采集{contactInfo.get("times_left", 0)}次达人联系方式'
            self.updateDaren[uid][contactKey] = contactInfo.get(contactMode)
            msg = f'成功采集到{self.updateDaren[uid]["nickname"]}的联系方式，还能采集{contactInfo.get("times_left", 0)}次达人联系方式'
            self.darenContactSuccNum += 1
            self.contactLimit -= 1
            self.updateDarenContact[uid] = {
                'id': self.updateDaren[uid]['id'],
                contactKey: contactInfo.get(contactMode),
                'nickname': self.updateDaren[uid]['nickname']
            }
            self.setScrollArea(msg, scrollArea=self.darenContactDialog)

    @Slot()
    def darenContactInfoFinished(self):
        """
        采集达人联系方式回调
        """
        self.darenContactThread.quit()
        self.darenContactThread.wait()
        msg = f'达人联系方式采集完毕。计划采集{self.darenContactNum}位达人的联系方式，实际成功采集{self.darenContactSuccNum}位的达人联系方式\r\n----------------------------------------'
        self.setScrollArea(msg, scrollArea=self.darenContactDialog)
        logging.info(f'准备上传的达人联系方式: {self.updateDaren}')
        # if self.darens:
        if self.updateDaren:
            logging.debug(f'开始上传达人信息!!')
            self.setupUpdateDarenContactThread()

    @Slot(dict)
    def setupDownloadDarenInfoThread(self, downloadBody):
        """
        启动调用上传达人信息接口线程        
        """
        self.downloadFromBackendApiThread = BackendApiThread(downloadBody=downloadBody, header={'Content-type': 'application/json', 'Authorization': f'Auth {self.jwt}'})
        self.downloadDarenInfoThread = QThread()
        self.downloadFromBackendApiThread.moveToThread(self.downloadDarenInfoThread)
        self.downloadFromBackendApiThread.downloadDarenInfoResp.connect(self.downloadDarenInfoResp)
        self.downloadFromBackendApiThread.finished.connect(self.downloadDarenInfoFinished)
        self.downloadDarenInfoThread.started.connect(self.downloadFromBackendApiThread.downloadDarenInfo)
        self.downloadDarenInfoThread.start()
    
    @Slot(dict)
    def downloadDarenInfoResp(self, uploadRes):
        """
        调用后台下载达人信息接口成功
        """
        logging.info(f'下载达人信息成功: {uploadRes}')
        # self.downloadProgress.emit(uploadRes.get('progress', 0))
        if not uploadRes.get('data', []):
            msgBox = QMessageBox(QMessageBox.Icon.Critical, "关闭", "达人数据下载失败，请查看日志",
                                 QMessageBox.StandardButton.NoButton, self)
            msgBox.addButton("关闭", QMessageBox.ButtonRole.RejectRole)
            msgBox.exec()
        else:
            self.downloadProgress.emit(uploadRes)

    @Slot(bool)
    def downloadDarenInfoFinished(self):
        """
        关闭后台下载达人信息接口线程       
        """
        logging.info(f'下载达人信息完成')
        self.downloadDarenInfoThread.quit()
        self.downloadDarenInfoThread.wait()

    def setupUploadDarenInfoThread(self):
        """
        启动调用上传达人信息接口线程        
        """
        self.upload2BackendApiThread = BackendApiThread(darens=self.darens, header={'Content-type': 'application/json', 'Authorization': f'Auth {self.jwt}'})
        self.uploadDarenInfoThread = QThread()
        self.upload2BackendApiThread.moveToThread(self.uploadDarenInfoThread)
        self.upload2BackendApiThread.uploadDarenInfoResp.connect(self.uploadDarenInfoResp)
        self.upload2BackendApiThread.finished.connect(self.uploadDarenInfoFinished)
        self.uploadDarenInfoThread.started.connect(self.upload2BackendApiThread.uploadDarenInfo)
        self.uploadDarenInfoThread.start()
    
    @Slot(dict)
    def uploadDarenInfoResp(self, uploadRes):
        """
        后台上传达人信息接口调用成功
        """
        uid = uploadRes.get("uid", 0)
        # res = uploadRes.get('res', False)
        id = uploadRes.get("id", 0)
        mobile = uploadRes.get("mobile", '')
        wechat = uploadRes.get("wechat", '')
        nickname = self.darens.get(uid, {}).get('nickname', '')
        logging.debug(f'uploadRes: {not nickname} - {not id}')
        if not nickname and not id:
            msg = f'达人信息上传失败'
        elif not id and nickname:
            msg = f'{nickname}达人信息上传失败'
        else:
            if self.contactMode == 1 and mobile != '':
                msg = f'{nickname}达人信息手机号已经采集成功不再重复采集'
                del self.darenContact[uid]
            elif self.contactMode == 2 and wechat != '':
                msg = f'{nickname}达人信息微信号已经采集成功不再重复采集'
                del self.darenContact[uid]
            else:
                exists = uploadRes.get('exists', 0)
                if exists == 0:
                    msg = f'{nickname}达人信息上传成功'
                else:
                    logging.debug(f'从今日特卖采集到的达人信息: {self.darens.get(uid)} - {uploadRes}')
                    msg, update = f'{nickname}达人的', False
                    if nickname != uploadRes.get('nickname'):
                        msg += f'昵称、'
                        update = True
                    # 头像不更新，因为url会一直变化
                    # if self.darens.get(uid, {}).get('avatar') != uploadRes.get('avatar'):
                    #     msg += f'、头像'
                    #     update = True
                    if self.darens.get(uid, {}).get('level') != uploadRes.get('level'):
                        msg += f'达人等级、'
                        update = True
                    if self.darens.get(uid, {}).get('fans_num') != uploadRes.get('fans_num'):
                        msg += f'粉丝数量、'
                        update = True
                    if update:
                        msg = f'{msg[0: len(msg) - 1]}发生变化，需要更新'
                        self.updateDarenInfo[uid] = self.darens.get(uid)
                    else:
                        msg = f'{nickname}达人信息上传成功，与上次采集无异'
                        self.darenNoUpdate += 1
            self.darens[uid]['id'] = id
        self.setScrollArea(msg)

    @Slot(bool)
    def uploadDarenInfoFinished(self):
        """
        关闭后台上传达人信息接口线程       
        """
        # logging.info(f'上传达人信息完成')
        self.setScrollArea(f'达人信息上传完成\r\n----------------------------------------')
        self.uploadDarenInfoThread.quit()
        self.uploadDarenInfoThread.wait()
        if self.jinritemaiThread.is_close:
            # 启动达人联系方式采集进程
            # self.setupDarenInfoThread()
            # 启动达人信息更新进程
            if self.updateDarenInfo:
                self.setupUpdateDarenInfoThread()
            else:
                self.mainUi.searchBtn.setEnabled(True)

    def setupUpdateDarenContactThread(self):
        logging.info(f'开始采集达人联系方式: {self.updateDaren}')
        self.updateDarenInfo2BackendApiThread = BackendApiThread(darens=self.updateDarenContact, header={'Content-type': 'application/json', 'Authorization': f'Auth {self.jwt}'})
        self.updateDarenContactThread = QThread()
        self.updateDarenInfo2BackendApiThread.moveToThread(self.updateDarenContactThread)
        self.updateDarenInfo2BackendApiThread.updateDarenInfoResp.connect(self.updateDarenContactResp)
        self.updateDarenInfo2BackendApiThread.finished.connect(self.updateDarenContactFinished)
        self.updateDarenContactThread.started.connect(self.updateDarenInfo2BackendApiThread.updateDarenInfo)
        self.updateDarenContactThread.start()

    @Slot(dict)
    def updateDarenContactResp(self, updateRes):
        uid = updateRes.get("uid", 0)
        id = updateRes.get("id", 0)
        # nickname = self.darens.get(uid, {}).get('nickname', '')
        nickname = updateRes.get("res", {}).get("nickname", "")
        qDebug(f'nickname: {updateRes} - {id}')
        if not nickname and not id:
            msg = f'达人联系方式编辑失败'
        elif not id and nickname:
            msg = f'{nickname}达人联系方式编辑失败'
        else:
            msg = f'{nickname}达人联系方式编辑成功'
        self.setScrollArea(msg, scrollArea=self.darenContactDialog)

    @Slot()
    def updateDarenContactFinished(self):
        """
        关闭后台上达人联系方式编辑接口线程       
        """
        # logging.info(f'上传达人信息完成')
        self.setScrollArea(f'达人信息编辑完成\r\n----------------------------------------', scrollArea=self.darenContactDialog)
        self.updateDarenContactThread.quit()
        self.updateDarenContactThread.wait()
        uids = list(self.darens)
        darensUpdate = list(self.updateDarenInfo)
        daren = len(uids) - len(darensUpdate) - self.darenNoUpdate
        self.darens = {}
        # self.setScrollArea(f'本次共成功采集{len(uids)}位达人的信息。其中，新增{daren}位达人信息，更新{len(darensUpdate)}位达人信息，还有{self.darenNoUpdate}位达人信息未发生变化', scrollArea=self.darenContactDialog)
        self.mainUi.searchBtn.setEnabled(True)

    def setupUpdateDarenInfoThread(self):
        self.updateDarenInfo2BackendApiThread = BackendApiThread(darens=self.updateDarenInfo, header={'Content-type': 'application/json', 'Authorization': f'Auth {self.jwt}'})
        # self.updateDarenInfo2BackendApiThread = BackendApiThread(darens=self.darens, header={'Content-type': 'application/json', 'Authorization': f'Auth {self.jwt}'})
        self.updateDarenInfoThread = QThread()
        self.updateDarenInfo2BackendApiThread.moveToThread(self.updateDarenInfoThread)
        self.updateDarenInfo2BackendApiThread.updateDarenInfoResp.connect(self.updateDarenInfoResp)
        self.updateDarenInfo2BackendApiThread.finished.connect(self.updateDarenInfoFinished)
        self.updateDarenInfoThread.started.connect(self.updateDarenInfo2BackendApiThread.updateDarenInfo)
        self.updateDarenInfoThread.start()

    @Slot(dict)
    def updateDarenInfoResp(self, updateRes):
        uid = updateRes.get("uid", 0)
        id = updateRes.get("id", 0)
        nickname = self.darens.get(uid, {}).get('nickname', '')
        if not nickname and not id:
            msg = f'达人信息编辑失败'
        elif not id and nickname:
            msg = f'{nickname}达人信息编辑失败'
        else:
            msg = f'{nickname}达人信息编辑成功'
        self.setScrollArea(msg)

    @Slot()
    def updateDarenInfoFinished(self):
        """
        关闭后台上达人信息编辑接口线程       
        """
        # logging.info(f'上传达人信息完成')
        self.setScrollArea(f'达人信息编辑完成\r\n----------------------------------------')
        self.updateDarenInfoThread.quit()
        self.updateDarenInfoThread.wait()
        uids = list(self.darens)
        darensUpdate = list(self.updateDarenInfo)
        daren = len(uids) - len(darensUpdate) - self.darenNoUpdate
        self.darens = {}
        self.setScrollArea(f'本次共成功采集{len(uids)}位达人的信息。其中，新增{daren}位达人信息，更新{len(darensUpdate)}位达人信息，还有{self.darenNoUpdate}位达人信息未发生变化')
        self.mainUi.searchBtn.setEnabled(True)

    # @Slot()
    # def updateDarenContactFinished(self):
    #     """
    #     关闭后台上达人联系方式编辑接口线程       
    #     """
    #     # logging.info(f'上传达人信息完成')
    #     self.setScrollArea(f'达人联系方式编辑完成\r\n----------------------------------------')
    #     self.darens = {}
    #     self.updateDarenInfoThread.quit()
    #     self.updateDarenInfoThread.wait()
    #     self.mainUi.searchBtn.setEnabled(True)

    def setupLoginThread(self):
        """
        启动登陆调用登陆后台接口线程
        """
        self.login2BackendThread = BackendApiThread()
        self.backendApiLoginThread = QThread()
        self.login2BackendThread.moveToThread(self.backendApiLoginThread)
        self.login2BackendThread.loginResp.connect(self.loginResp)
        self.login2BackendThread.finished.connect(self.loginFinished)
        self.backendApiLoginThread.started.connect(self.login2BackendThread.login)
        self.backendApiLoginThread.start()

    @Slot(dict)
    def loginResp(self, userInfo):
        """
        调用后台登陆接口成功回调
        """
        if not userInfo.get('jwt', None):
            self.close()
        self.contactLimit = userInfo.get('contact_times', 100) - userInfo.get('already_contact_times', 100)
        self.contactMode = userInfo.get('contact_mode', 1)
        self.jwt = userInfo.get('jwt', '')

        logging.info(f'contactLimit: {self.contactLimit}')
        if self.contactLimit == 0:
            msgBox = QMessageBox(QMessageBox.Icon.Critical, "关闭", "达人联系信息采集已达上限，请明天再试",
                                 QMessageBox.StandardButton.NoButton, self)
            msgBox.addButton("关闭", QMessageBox.ButtonRole.RejectRole)
            msgBox.exec()
        else:
            msg = f'登陆成功，当前账号今天还可采集{self.contactLimit}次达人信息。系统设定当前采集的为达人的{"手机号码" if self.contactMode == 1 else "微信号"}'
            self.setScrollArea(msg)

    @Slot()
    def loginFinished(self):
        """
        关闭后台登陆线程
        """
        logging.error(f'登陆完成')
        self.backendApiLoginThread.quit()
        self.backendApiLoginThread.wait()

    def setupDarenListThread(self):
        """
        初始化采集达人列表接口线程
        """
        self.jinritemaiThread = JinritemaiThread(cookies=self.cookies, verifyFp=self.verifyFp,
                                                msToken=self.msToken, screenInfo=self.screenInfo,
                                                ua=self.userAgent, body=self.searchFilterWidgets.queryBody,
                                                contactLimit=self.contactLimit, cond=self.cond, mutex=self.mutex)
        self.thread = QThread()
        self.jinritemaiThread.moveToThread(self.thread)
        self.jinritemaiThread.darenListResp.connect(self.darenListResp)
        self.jinritemaiThread.finished.connect(self.darenListFinished)
        self.thread.started.connect(self.jinritemaiThread.getDarenList)
        self.thread.start()

    def closeCollection(self):
        # logging.debug(f'darenList: {self.thread.isRunning()} - {self.thread.isFinished()}')
        # logging.debug(f'darenInfo: {self.uploadDarenInfoThread.isRunning()}')
        if self.thread and self.thread.isRunning():
            self.jinritemaiThread.close()
            self.setScrollArea(f'关闭采集程序')
        """
        elif hasattr(self, "darenContactThread") and self.darenContactThread.isRunning():
            self.JinritemaiThread.close()
            self.setScrollArea(f'关闭采集程序')
        """

    def pauseCollection(self):
        if not self.jinritemaiThread.is_pause:
            self.jinritemaiThread.pause()
            btnTxt = '继续'
            msg = '暂停'
        else:
            self.jinritemaiThread.resume()
            btnTxt = '暂停'
            msg = '继续'

        self.mainUi.pauseBtn.setText(btnTxt)
        msg = f'{msg}采集程序\r\n----------------------------------------'
        self.setScrollArea(msg)

    def resetDarenList(self):
        self.darens = {}
        self.updateDaren = {}

    def startCollection(self):
        """
        开始采集按钮的信号槽
        """
        try:
            self.getContactMode()
            self.parseCookies() 
            self.resetDarenList()
            if not self.searchFilterWidgets:
                self.searchFilterWidgets = SearchFilterWidgets(parentWidget=self, showWidgets=False)

            self.setupDarenListThread()
            self.mainUi.searchBtn.setEnabled(False)
        except ValueError as e:
            msgBox = QMessageBox(QMessageBox.Icon.Critical, "关闭", str(e),
                                 QMessageBox.StandardButton.NoButton, self)
            msgBox.addButton("关闭", QMessageBox.ButtonRole.RejectRole)
            msgBox.exec()
        except KeyError as e:
            msgBox = QMessageBox(QMessageBox.Icon.Critical, "关闭", str(e),
                                QMessageBox.StandardButton.NoButton, self)
            msgBox.addButton("关闭", QMessageBox.ButtonRole.RejectRole)
            msgBox.exec()
        except Exception as e:
            logging.error(f'eee {e}')

    @Slot(bool)
    def searchFilterWidgetsShow(self, isShow):
        """
        show信号槽, 若是错误信息弹出msgBox
        """
        if not isShow:
            msgBox = QMessageBox(QMessageBox.Icon.Critical, "关闭", '搜索条件获取失败，具体原因请查看日志',
                                 QMessageBox.StandardButton.NoButton, self)
            msgBox.addButton("关闭", QMessageBox.ButtonRole.RejectRole)
            msgBox.exec()

    def showSearchFilterWidgets(self):
        """
        弹出搜索条件界面
        """
        try:
            self.parseCookies()
            if not self.searchFilterWidgets:
                self.searchFilterWidgets = SearchFilterWidgets(parentWidget=self)
            else:
                self.searchFilterWidgets.show()
            
        except ValueError as e:
            msgBox = QMessageBox(QMessageBox.Icon.Critical, "关闭", str(e),
                                 QMessageBox.StandardButton.NoButton, self)
            msgBox.addButton("关闭", QMessageBox.ButtonRole.RejectRole)
            msgBox.exec()
        except KeyError as e:
            msgBox = QMessageBox(QMessageBox.Icon.Critical, "关闭", str(e),
                                QMessageBox.StandardButton.NoButton, self)
            msgBox.addButton("关闭", QMessageBox.ButtonRole.RejectRole)
            msgBox.exec()
